<script lang="ts" setup>
const props = defineProps({
  numValue: Number,
});
const startNum = ref(0);
const animatedNumber = ref(props.numValue);
watch(
  () => props.numValue,
  (v) => {
    animateNumber(startNum.value, v, 500, (currentValue: number) => {
      animatedNumber.value = Math.round(currentValue);
      startNum.value = v;
    });
  }
);
function animateNumber(
  start: number,
  end: number,
  duration: number,
  callback: Function
) {
  const fps = 1000 / 60; // 每秒帧数，默认60
  const totalFrames = Math.round(duration / fps); // 计算总帧数
  const increment = (end - start) / totalFrames; // 计算每帧的增量
  let current = start;
  let frame = 0;

  const animate = () => {
    if (frame < totalFrames) {
      frame++;
      current += increment;
      callback(current);
      requestAnimationFrame(animate);
    } else {
      callback(end);
    }
  };

  animate();
}
</script>

<template>
  <div>{{ animatedNumber }}<slot></slot></div>
</template>
